<?php

namespace app\zyhsapi\controller\v4;

use app\common\lib\Aes;
use app\common\lib\IAuth;
use app\zyhsapi\controller\ZyhsAuth;
use app\zyhsapi\model\ZyhsAppleidUser;
use app\zyhsapi\model\ZyhsQq;
use app\zyhsapi\model\ZyhsRecode;
use app\zyhsapi\model\ZyhsUser;
use app\zyhsapi\model\ZyhsWechat;
use app\zyhsapi\model\ZyhsWeibo;
use app\zyhsapi\service\CacheZyhs;
use app\zyhsapi\service\JiGuang;
use think\Log;
use XznsTools\cache\zyhs\CacheManageZyhs;

class Info extends ZyhsAuth
{
    public function phoneOneClickBind()
    {
        $loginToken = input('login_token/s');
        $appConfig = config('zyhsapp');
        $telResData = (new JiGuang())->JGtokenGetMobile($loginToken);
        if ($telResData['success'])
        {
            $tel = $telResData['mobile'];
            //准币测试号
            if (isset($appConfig['coin_mobile'][$tel]) && $appConfig['coin_mobile'][$tel] === 2)
            {
                return show(418, '该手机号已使用，请更换其他手机号');
            }
            $areaCode = 86;
            $mobileTel = $tel;
            $user = $this->CheckUserTel($tel, $areaCode);
            $userModel = new ZyhsUser();
            if ($user && !empty($user))
            {
                // 当前账号没有订单 没有 档案 可以废弃合并到绑定手机号账号
                $wechatModel = new ZyhsWechat();
                $qqModel = new ZyhsQq();
                $weiboModel = new ZyhsWeibo();
                $appleidUserModel = new ZyhsAppleidUser();
                //判断用户是否绑定微信
                $wechatInfo = $wechatModel->where('uid', $this->user['id'])->field('id,unionid')->find();
                if ($wechatInfo)
                {   // 绑定了微信
                    // 判断要绑定的手机号账号是否绑定了微信
                    $wechatId2 = $wechatModel->where('uid', $user['id'])->value('id');
                    if ($wechatId2)
                    {
                        $loginToken = md5(uniqid(md5(microtime(true)), true));
                        CacheZyhs::set('bindTel:loginToken:' . $mobileTel, $loginToken, 3600);
                        return show(config('code.success'), '绑定失败', [
                            'type' => 2,
                            'access_token_info' => null,
                            'sync_recode_info' => [],
                            'tel_user_name' => $user['nickname'],
                            'login_token' => $loginToken,
                            'tel' => (new Aes())->encryptWithOpenssl($tel, 'zyhsapp'),
                        ]);
                    }
                }
                //判断用户是否绑定了qq
                $qqInfo = $qqModel->where('uid', $this->user['id'])->field('id,unionid')->find();
                if ($qqInfo)
                {   // 绑定了QQ
                    // 判断要绑定的手机号账号是否绑定了QQ
                    $qqId2 = $qqModel->where('uid', $user['id'])->value('id');
                    if ($qqId2)
                    {
                        $loginToken = md5(uniqid(md5(microtime(true)), true));
                        CacheZyhs::set('bindTel:loginToken:' . $mobileTel, $loginToken, 3600);
                        return show(config('code.success'), '绑定失败', [
                            'type' => 2,
                            'access_token_info' => null,
                            'sync_recode_info' => [],
                            'tel_user_name' => $user['nickname'],
                            'login_token' => $loginToken,
                            'tel' => (new Aes())->encryptWithOpenssl($tel, 'zyhsapp'),
                        ]);
                    }
                }
                //判断用户是否绑定了微博
                $wbInfo = $weiboModel->where('uid', $this->user['id'])->field('id,wbuid')->find();
                if ($wbInfo)
                {   // 绑定了微博
                    // 判断要绑定的手机号账号是否绑定了微博
                    $wbId2 = $weiboModel->where('uid', $user['id'])->value('id');
                    if ($wbId2)
                    {
                        $loginToken = md5(uniqid(md5(microtime(true)), true));
                        CacheZyhs::set('bindTel:loginToken:' . $mobileTel, $loginToken, 3600);
                        return show(config('code.success'), '绑定失败', [
                            'type' => 2,
                            'access_token_info' => null,
                            'sync_recode_info' => [],
                            'tel_user_name' => $user['nickname'],
                            'login_token' => $loginToken,
                            'tel' => (new Aes())->encryptWithOpenssl($tel, 'zyhsapp'),
                        ]);
                    }
                }
                //判断用户是否绑定了apple
                $appleInfo = $appleidUserModel->where('uid', $this->user['id'])->field('id,apple_id')->find();
                if ($appleInfo)
                {   // 判断要绑定的手机号账号是否绑定了微博
                    $appleId2 = $appleidUserModel->where('uid', $user['id'])->value('id');
                    if ($appleId2)
                    {
                        $loginToken = md5(uniqid(md5(microtime(true)), true));
                        CacheZyhs::set('bindTel:loginToken:' . $mobileTel, $loginToken, 3600);
                        return show(config('code.success'), '绑定失败', [
                            'type' => 2,
                            'access_token_info' => null,
                            'sync_recode_info' => [],
                            'tel_user_name' => $user['nickname'],
                            'login_token' => $loginToken,
                            'tel' => (new Aes())->encryptWithOpenssl($tel, 'zyhsapp'),
                        ]);
                    }
                }
                // 开始进行绑定 合并
                $id = (int)($user['id']);
                if ($wechatInfo)
                { // 微信合并
                    $wechatModel->where('id', $wechatInfo['id'])->update(['uid' => $id]);
                    CacheManageZyhs::getInstance()->setCacheConfig('wechat.wechat', $wechatInfo['unionid'] . '-1')->rmCache();
                }
                if ($qqInfo)
                { // QQ合并
                    $qqModel->where('id', $qqInfo['id'])->update(['uid' => $id]);
                    CacheManageZyhs::getInstance()->setCacheConfig('user.qq', $qqInfo['unionid'] . '-1')->rmCache();
                }
                if ($wbInfo)
                { // 微博合并
                    $weiboModel->where('id', $wbInfo['id'])->update(['uid' => $id]);
                    CacheManageZyhs::getInstance()->setCacheConfig('user.weibo', $wbInfo['wbuid'] . '-1')->rmCache();
                }
                if ($appleInfo)
                { // apple合并
                    $appleidUserModel->where('id', $appleInfo['id'])->update(['uid' => $id]);
                    CacheManageZyhs::getInstance()->setCacheConfig('user.apple', $appleInfo['apple_id'])->rmCache();
                }
                // 使用绑定手机号账号登录
                $token = IAuth::setAppLoginToken($tel); // 生成token
                $data = [
                    'token' => $token,
                    'token_expire' => strtotime("+" . $appConfig['login_time_out_day'] . " days"),
                ];
                // 更新用户信息
                $userModel->updateUserinfo(['id' => $id], $data);
                // 更新旧数据信息
                $userModel->updateUserinfo(['id' => $this->user['id']], ['token' => '', 'token_expire' => '']);

                // 获取自己档案ID
                $recordInfo = (new ZyhsRecode())->getRecodeLists($id, 1);
                $result = [
                    'id' => $id,
                    'self_rid' => $recordInfo ? (int)($recordInfo['id'] ?? 0) : 0,
                    'user_access_token' => (new Aes())->encryptWithOpenssl($token . "||" . $user['id'], 'zyhsapp'),
                    'has_bind_tel' => 1,     // 是否绑定了手机号 1绑定了 0未绑定
                ];

                return show(config('code.success'), '绑定成功', [
                    'type' => 1,
                    'access_token_info' => $result,
                    'sync_recode_info' => [],
                    'tel_user_name' => '',
                    'login_token' => '',
                    'tel' => (new Aes())->encryptWithOpenssl($tel, 'zyhsapp'),
                ]);
            }

            // 若未注册
            try
            {
                // 开始绑定手机号
                $bindInfo = ['tel' => $mobileTel, 'temporary_tel' => '', 'tel_bind_time' => 0];
                $userModel->updateUserinfo(['id' => $this->user['id']], $bindInfo);
                // 绑定成功 查看手机号是否
                $syncRecodeInfo = (new ZyhsRecode())->getAccountRecodeNumByTelZyhs($mobileTel, $this->user['id']);
            }
            catch (\Exception $e)
            {
                Log::write($this->user['id'] . '绑定手机号失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error', true);
                return show(0, '绑定失败');
            }

            return show(config('code.success'), '绑定成功', [
                'type' => 1,
                'access_token_info' => null,
                'sync_recode_info' => $syncRecodeInfo,
                'tel_user_name' => '',
                'login_token' => '',
                'tel' => (new Aes())->encryptWithOpenssl($tel, 'zyhsapp'),
            ]);
        } else
        {
            return show(418, '一键绑定失败');
        }
    }
}